/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       multitexturedmaterial.frag
 * Author:     karooolek
 * Created on: 2009-06-23
 *
 **********************************************************************************************************************/

STRINGIZE(

varying vec4 position;
varying mat3 tbn;

uniform sampler2D texture;
uniform sampler2D normalMap;
uniform sampler2D specMap;

void main()
{
    // global ambient lighting
    gl_FragColor = gl_FrontLightModelProduct.sceneColor;

    // calculate normal 
    vec3 N = normalize(tbn * (2.0 * vec3(texture2D(normalMap, vec2(gl_TexCoord[0]))) - 1.0));
    
    // get ambient/diffuse color
    vec4 tex = texture2D(texture, vec2(gl_TexCoord[0]));
    
    // get specular from specular map
    vec4 spec = texture2D(specMap, vec2(gl_TexCoord[0]));
    
    // calculate view vector
    vec3 V = normalize(-vec3(position));
    
    // lighting for each light
    for(int i = 0; i != 8; ++i)
    {
        vec4 color = vec4(0.0);
        
        // calculate light vector and distance
        vec3 L = vec3(gl_LightSource[i].position - position);
        float d = length(L);
        L = normalize(L);
        
        // half vector
        vec3 H = normalize(L + V);
        
        // calculate diffuse
        color += gl_FrontLightProduct[i].diffuse * tex * max(dot(N, L), 0.0);
        
        // TODO FINISH calculate specular
        color += gl_FrontLightProduct[i].specular * spec * pow(max(dot(N, H), 0.0), gl_FrontMaterial.shininess * spec.a);
        
        // distance attenuation
        color *= 1.0 / (
            gl_LightSource[i].constantAttenuation +
            gl_LightSource[i].linearAttenuation * d +
            gl_LightSource[i].quadraticAttenuation * d * d
            );
        
        // spotlight attenuation
        float spotCos = dot(normalize(gl_LightSource[i].spotDirection), -L);
        color *= smoothstep(gl_LightSource[i].spotCutoff - 1.0, gl_LightSource[i].spotExponent -1.0, spotCos);
        
        // ambient light
        color += gl_FrontLightProduct[i].ambient * tex;
        
        // update fragment color
        gl_FragColor += color;
    }
    
//    // fog
//    float fogCoord = clamp((-position.z  - gl_Fog.start) / (gl_Fog.end - gl_Fog.start), 0.0, 1.0);
//    gl_FragColor = mix(gl_FragColor, gl_Fog.color, fogCoord);

    // clamp color
    gl_FragColor = clamp(gl_FragColor, 0.0, 1.0);
}

) // STRINGIZE
